import './index.scss';
import React, { Component } from 'react';
import axios from 'axios';
import logoImg from 'images/logo-img.png';
import qs from 'qs';
import DatePicker from 'components/DatePicker';
import moment from 'moment';
import Compressor from 'compressorjs';
import { loadingOn, loadingOff } from 'components/Loading';
import jiujia from './jiujia.jpg';
import MemorizedState from 'hoc/MemorizedState';
import Notice from '../Notice';
	
@MemorizedState({ ignore: ['finished',  'shops', 'subItem']})
class Page extends Component {
		state = {
			shops: '',
			subItem:''
		}
	
		componentDidUpdate() {
			this.props.memorize(this.state);
		}
	
		componentWillMount() {
			this.setState({
				...this.props.memory
			});
			document.title = '阿里健康疫苗预约登记表';
			let that = this;
			axios.get('https://appapi.jzdoctor.com/config/subscribe_hospital.php').then(res => {
				that.setState({ shops: res.data });
			});

			axios.get('https://appapi.jzdoctor.com/config/subscribe_item.php').then(res => {
				console.log(res.data)
				that.setState({ subItem: res.data });
			});
  }

	componentDidMount () {
		(function(){
			window.alert = function(name){
				let iframe = document.createElement("IFRAME");
				iframe.style.display="none";
				iframe.setAttribute("src", 'data:text/plain');
				document.documentElement.appendChild(iframe);
				window.frames[0].window.alert(name);
				iframe.parentNode.removeChild(iframe);
			}
		})();
	}

  submit = () => {
    let { orderNo, name, sex, mobile, cardNo, bookName, bookShop, bookTime,cardType,code,preview} = this.state;

    if (!orderNo) return alert('请您输入订单号');
    if (!name) return alert('请您输入姓名');
    if (!sex) return alert('请您输入性别');
    if (!mobile) return alert('请您输入手机号');
    if (!cardNo) return alert('请您输入证件号');
    if (!bookName) return alert('请您选择预约项目');
		if (!preview) return alert('请您上传电子凭证核销码截图');
		if (!bookTime) return alert('请您选择预约日期');
    if (!bookShop || bookShop === '请选择预约门店') return alert('请您选择预约门店');
    // if (isNaN(payAmount) || !payAmount) return alert('请您输入金额');

    if (this.requesting) return;
    this.requesting = true;

    let data = { ...this.state,platform:2 };
    data.channel = qs.parse(location.href.split('?')[1]).channel;
    delete data.shops;

    axios.post(`${APP_CONFIG.appServer}/common/review/aliHealthVaccine/saveBook`, data).then(res => {
      if (res.data.code == 0) {
        this.setState({
          finished: true
				});
				this.props.clearMemorized();
      }
      else {
        alert(res.data.msg);
        this.requesting = false;
      }
    }).finally(res => {
      this.requesting = false;
    });
  }

  updateField = (fieldName, event) => {
    this.setState({ [fieldName]: typeof event ==='string' ? String(event).trim() : String(event.target.value).trim() });

    if(fieldName === 'cardType'){
    	this.setState({
				cardNo:''
			})
		}
  }

	setDate = (val) => {
		this.setState({
			bookTime:moment(val).format('YYYY-MM-DD HH:mm:ss')
		})
	}

	handleUpload = (input) => {
		//  format check
		let files = input.target.files || input.dataTransfer.files;

		if (!files.length) return;

		let isValid = [].every.call(files, file => /\.jpe?g|png$/.test(file.name.toLowerCase()));

		if (!isValid) return alert('请选择图片');

		loadingOn();

		//  compress before preview & uploading
		new Compressor(files[0], {
			quality: 0.4,
			convertSize: 200000,
			maxWidth: 1000,
			maxHeight: 1000,
			success: (result) => {
				let reader = new FileReader();

				reader.onload = (e) => {
					let src = e.target.result;

					//  set preview
					this.setState({
						preview: src
					});

					//  uploading
					let bodyFormData = new FormData();
					bodyFormData.append('image', files[0]);

					axios.post(`${APP_CONFIG.appServer}/common/review/file/uploadImage`, bodyFormData, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					}).then(res => {
						loadingOff();

						if (res.data.code !== 0) {
							alert('上传照片失败, 请您重新上传');
							this.setState({
								preview: '',
								url: ''
							})
						}
						else {
							this.setState({
								url: res.data.data.url
							})
						}
					}).catch(e => {
						loadingOff();
					});
				};

				reader.onerror = (e) => {
					loadingOff();
				}

				reader.readAsDataURL(result);
			},
			error: () => {
				loadingOff();
			}
		});
	}

  render() {
    if (this.state.finished) return <h1 style={{padding: '20px', textAlign: 'center'}}>提交成功, 请关闭本页</h1>;

    return (
      <div className="misc-booking misc-booking-register-board">
        <div className="misc-booking-register-hd">
          <h1>阿里健康海外预约信息登记表</h1>
          <p>【请详细准确填写资料】</p>
          <p>【若资料信息有误可能导致无法为您安排接种】</p>
          <img src={logoImg} alt="" style={{width: '100%', marginBottom: '10px'}}/>
        </div>

        <div className="misc-booking-register-bd">
          <div className="rules">
          <p className={'notice'}>※注意事项（请认真阅读）：</p>
          1、该表格为确认预约登记表，不填写提交则默认放弃接种，将不予安排接种门诊；预约成功后，用户将于至少2个工作日接收到预约成功短信，接到预约成功短信后便可安排行程（如遇节假日或活动期，预约成功短信可能会延迟，为了避免耽误您的行程，请及时提前填写信息预约）；<br/>
						2、预约请提前至少一周，填写该表格时，预约时间请选择填写表格日期至少一周后；如紧急订单可能会系统审核超时，导致您预约错误无法按时接种；<br/>
						3、核销码作为确认预约凭证，不核销不予安排接种，再接种前一天会进行核销，接种当天带着个人证件（身份证、港澳通行证，部分用户如使用护照请带上护照及身份证）到前台登记即可接种疫苗。请务必在收到确认预约成功短信后，再安排行程，请勿在未收到确认预约成功短信前安排行程，避免造成您的损失；；<br/>
						4、产品使用前，若对本产品不满意，可随时联系退款；未接种或未享受产品配套服务时，均可全额退款，无需担心核销后不可退款；<br/>
						5、若已开始接种疫苗或已享受产品配套服务，则不可退款；<br/>
						6、有任何疑问，欢迎致电联系（021-62141588）；或进入阿里健康旗舰店咨询旺旺客服；<br/>
						7、更多资讯欢迎关注：官方微博：彩虹育儿 ； 官方微信公众号：彩虹育儿 ；更多预约优惠可下载App：彩虹育儿进行查看
          </div>
          <div className="form">
            <div className="form-row">
              <div className="form-label">
                <p>阿里健康订单号：<span className={'require'}>*</span></p>
                <small>(请准确填写18位数订单号)</small>
              </div>
              <div className="form-item">
                <input type="text" className="input-text" onChange={this.updateField.bind(this, 'orderNo')} value={this.state.orderNo} />
              </div>
            </div>
            <div className="form-row">
              <div className="form-label">
                <p>姓名：<span className={'require'}>*</span></p>
              </div>
              <div className="form-item">
                <input type="text" className="input-text" onChange={this.updateField.bind(this, 'name')} value={this.state.name} />
              </div>
            </div>
						<div className="form-row">
							<div className="form-label form-label-large">
								<p>手机：<span className={'require'}>*</span></p>
							</div>
							<div className="form-item">
								<input type="tel" className="input-text input-text-large" onChange={this.updateField.bind(this, 'mobile')} value={this.state.mobile} placeholder="请输入您的11位手机号码" />
							</div>
						</div>
						<div className="form-row">
							<div className="form-label">
								<p>证件：<span className={'require'}>*</span></p>
							</div>
							<div className="form-item radio-group">
								<p onClick={this.updateField.bind(this, 'cardType', '0')}>
									<input type="radio" name="cardType" value="0" checked={this.state.cardType === '0'}/>身份证
									{
										this.state.cardType === '0' &&								<p className="form-item-ib">
											<input type="text" className="input-text" onChange={this.updateField.bind(this, 'cardNo')} value={this.state.cardNo} />
										</p>
									}

								</p>
								<p onClick={this.updateField.bind(this, 'cardType', '1')}>
									<input type="radio" name="cardType" value="1" checked={this.state.cardType === '1'}/>
									港澳通行证
									{
										this.state.cardType === '1' &&								<p className="form-item-ib">
											<input type="text" className="input-text" onChange={this.updateField.bind(this, 'cardNo')} value={this.state.cardNo} />
										</p>
									}
								</p>
								<p onClick={this.updateField.bind(this, 'cardType', '2')}>
									<input type="radio" name="cardType" value="2" checked={this.state.cardType === '2'}/>
									护照
									{
										this.state.cardType === '2' &&								<p className="form-item-ib">
											<input type="text" className="input-text" onChange={this.updateField.bind(this, 'cardNo')} value={this.state.cardNo} />
										</p>
									}
								</p>
					    </div>
						</div>
						<div className="form-row">
							<div className="form-label">
								<p>性别：<span className={'require'}>*</span></p>
							</div>
							<div className="form-item radio-group">
								<p onClick={this.updateField.bind(this, 'sex', '男')}><input type="radio" name="sex" value="男" checked={this.state.sex === '男'}/>男</p>
								<p onClick={this.updateField.bind(this, 'sex', '女')}><input type="radio" name="sex" value="女" checked={this.state.sex === '女'}/>女</p>
							</div>
						</div>

            <div className="form-row">
              <div className="form-label">
                <p>预约项目：<span className={'require'}>*</span></p>
              </div>
              <div className="form-item radio-group">
								<select onChange={this.updateField.bind(this, 'bookName')} value={this.state.bookName}>
									{
										this.state.subItem.split('\n').filter(i => i.trim()).map((item, index) => <option value={item.trim()} key={index}>{item.trim()}</option>)
									}
								</select>
              </div>
            </div>
            <div className="form-row">
              <div className="form-label">
                <p>预约门店：<span className={'require'}>*</span></p>
              </div>
              <div className="form-item">
                <select onChange={this.updateField.bind(this, 'bookShop')} value={this.state.bookShop}>
                  {
                    this.state.shops.split('\n').filter(i => i.trim()).map((item, index) => <option value={item.trim()} key={index}>{item.trim()}</option>)
                  }
                </select>
              </div>
            </div>
            <div className="form-row">
              <div className="form-label">
                <p>预约日期：<span className={'require'}>*</span></p>
								<small>(门店营业时间不同，预约时间请按照门诊营业时间进行预约，如预约时间错误，将会退回重新预约时间)</small>
              </div>
              <div className="form-item">
								<DatePicker
									maxDate={new Date(2030, 8, 15, 10, 30, 0)}
									date={moment(new Date()).toDate()}
									onChange={this.setDate}
									mode={'datetime'}
								>
									<p className={'data-picker'}>
										<span className="icon-calender"> </span>
										{
											this.state.bookTime || '选择日期'
										}

									</p>

							</DatePicker>
              </div>
            </div>
            <div className="form-row">
              <div className="form-label">
                <p>电子核销码截图：<span className={'require'}>*</span></p>
                <small>(若无法截图上传，可截图订单后在下方填写10位数核销码)</small>
								<small>Image formats like .jpg, .jpeg .png are supported. </small>
              </div>
              <div className="form-item">
								<div className="form-item">
									<input
										type="file"
										accept="image/*"
										onChange={e => this.handleUpload(e)}
										onClick={e => (e.target.value = null)}
										className="uploadInput"
										placeholder="点击选择图片"
									/>
									<img src={this.state.preview} style={{width: '30%', display: 'block', marginTop: '20px'}} alt=""/>
								</div>

              </div>
            </div>

						<div className="form-row">
							<div className="form-label">
								<p>电子凭证核销码 ：</p>
								<small>(无法截图上传时，选择手动输入填写，非必填)</small>
							</div>
							<div className="form-item">
								<input type="tel" className="input-text" onChange={this.updateField.bind(this, 'code')} value={this.state.code} />
							</div>
							<p>(参考下方图示，若上传错误将导致无法预约成功)</p>
							<p>(如有疑问请及时拨打预约咨询热线反馈，避免耽误您宝贵的预约时间)
							</p>
							<p>示例：</p>
						</div>

						<div className="form-row">
							<img src={jiujia} alt="" className={'jiujia'}/>
						</div>
            <div className="form-row">
                <button className="button" onClick={this.submit}>提交</button>
            </div>
						<Notice></Notice>
          </div>
        </div>
      </div>
    );
  }
}

export default Page;